package bc.swim2.web.servlet;

import java.io.IOException;

import javax.naming.Context;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bc.swim2.ejb.session.AbilityRequestManagerBeanRemote;

/**
 * Servlet implementation class AbilityRequestServlet
 */
public class AbilityRequestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AbilityRequestServlet() {
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("methodName").equals("remove")) {
			removeAbilityRequest(request, response);
		}

		if (request.getParameter("methodName").equals("add")) {
			addAbilityRequest(request, response);
		}
	}

	private void addAbilityRequest(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			String arName = request.getParameter("name");
			String arDescription = request.getParameter("description");

			Object ref2 = ctx.lookup("AbilityRequestManagerBean/remote");
			AbilityRequestManagerBeanRemote arm = (AbilityRequestManagerBeanRemote) ref2;

			arm.insertAbilityRequest(arName, arDescription);

			response.sendRedirect("MainServlet?to=RegisteredUserHome");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void removeAbilityRequest(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			int abilityRequestId = Integer.parseInt(request
					.getParameter("abilityRequestId"));
			Object ref3 = ctx.lookup("AbilityRequestManagerBean/remote");
			AbilityRequestManagerBeanRemote arm = (AbilityRequestManagerBeanRemote) ref3;
			arm.removeAbilityRequest(abilityRequestId);

			response.sendRedirect("MainServlet?to=ShowAbilityRequests");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
